#!/bin/sh
# freerds control script
# Written : 1-13-2006 - Mark Balliet - posicat@pobox.com
# maintained by Jay Sorg
# chkconfig: 2345 11 89
# description: starts freerds

### BEGIN INIT INFO
# Provides: freerds
# Required-Start:
# Required-Stop:
# Should-Start:
# Should-Stop:
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Start and stop freerds
# Description: starts freerds
### END INIT INFO

SBINDIR=${FREERDS_SBIN_PATH}
CFGDIR=${FREERDS_CFG_PATH}
PIDDIR=${FREERDS_PID_PATH}
LOG=/dev/null

if ! test -x $SBINDIR/freerds
then
	echo "freerds is not executable"
	exit 0
fi
if ! test -x $CFGDIR/startwm.sh
then
	echo "startwm.sh is not executable"
	exit 0
fi

freerds_start()
{
	echo -n "Starting FreeRDS..."
	$SBINDIR/freerds >> $LOG
	echo "."
	sleep 1
	return 0;
}

freerds_stop()
{
	echo -n "Stopping FreeRDS..."
	$SBINDIR/freerds --kill >> $LOG
	echo "."
	return 0;
}

is_freerds_running()
{
	ps u --noheading -C freerds | grep -q -i freerds
	if test $? -eq 0
	then
		return 1;
	else
	return 0;
	fi
}

check_up()
{
	# Cleanup : If xrdp isn't running, but the pid exists, erase it.
	is_freerds_running
	if test $? -eq 0
	then
		if test -e $PIDDIR/freerds.pid
		then
			rm $PIDDIR/freerds.pid
		fi
	fi
	return 0;
}

case "$1" in
	start)
		check_up
		is_freerds_running
		if ! test $? -eq 0
		then
			echo "FreeRDS is already running."
			exit 1
		fi
		freerds_start
		;;
	stop)
		check_up
		is_freerds_running
		if test $? -eq 0
		then
			echo "FreeRDS is not running."
		fi
		freerds_stop
		;;
	force-reload|restart)
		check_up
		echo "Restarting FreeRDS..."
		freerds_stop
		is_freerds_running
		while ! test $? -eq 0
		do
			check_up
			sleep 1
			is_freerds_running
		done
		freerds_start
		;;
	*)
		echo "Usage: freerds.sh {start|stop|restart|force-reload}"
		exit 1
esac

exit 0
